<template>
  <basic-container>
    <avue-crud :option="option"
               :search.sync="search"
               :table-loading="loading"
               :data="data"
               :page.sync="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @sort-change="sortChange"
               >
      
      <template slot-scope="{}" slot="rpiNoSearch">
        <select-page ref="searchRpiSelect" label="rpiName" value="rpiNo" :select.sync="search.rpiNo" :url="website.searchLink.merchantUrl" placeholder-text="商户" filter-key="searchParam"></select-page>
      </template>
      <template slot-scope="{row}"
            slot="stlAmt">
        <span class="money-text">{{row.stlAmt}} 元</span>
      </template>
      <template slot-scope="{row}"
            slot="payAmt">
        <span class="money-text">{{row.payAmt}} 元</span>
      </template>
      <template slot-scope="{row}"
            slot="adjustAmt">
        <span class="money-text">{{row.adjustAmt}} 元</span>
      </template>
      <template slot-scope="{row}"
            slot="mercServiceAmt">
        <span class="money-text">{{row.mercServiceAmt}} 元</span>
      </template>
    </avue-crud>
    <el-dialog title="数据导入"
               append-to-body
               :visible.sync="excelBox"
               width="555px">
      <avue-form :option="excelOption"
                 v-model="excelForm"
                 :upload-after="uploadAfter"
                 :upload-delete="uploadDelete">
        <template slot="excelTemplate">
          <el-button type="primary"
                     @click="handleTemplate">
            点击下载<i class="el-icon-download el-icon--right"></i>
          </el-button>
        </template>
      </avue-form>
    </el-dialog>
  </basic-container>
</template>

<script>
import { getList } from "@/api/rb-oem/settlementProgress/settlement_progress";
import {mapGetters} from "vuex";
import {
  getToken
} from '@/util/auth';
import { dateFormat } from '@/util/date';
import selectPage from "@/components/select-page/select-page";

export default {
  components: {
    selectPage
  },
  data() {
    return {
      form: {},
      query: {},
      search: {
        stlStartDate: dateFormat(new Date(new Date().getTime() - 3600 * 1000 * 24),"yyyy-MM-dd").replace(/-/g, ""),
        stlEndDate: dateFormat(new Date(new Date().getTime() - 3600 * 1000 * 24),"yyyy-MM-dd").replace(/-/g, "")
      },
      loading: true,
      excelBox: false,
      page: {
        pageSize: 10,
        pageNum: 1,
        // stlStartDate: dateFormat(new Date(new Date().getTime() - 3600 * 1000 * 24),"yyyy-MM-dd"),
        // stlEndDate: dateFormat(new Date(new Date().getTime() - 3600 * 1000 * 24),"yyyy-MM-dd"),
        total: 0
      },
      selectionList: [],
      option: {
       height: "calc(50vh - 50px)",
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        viewBtn: true,
        selection: true,
        searchMenuSpan: 6,
        emptyBtn: false,
        columnBtn: false,
        column: [
          {
            label: "结算时间",
            prop: "payDate",
            type: "input",
            //sortable: true,
            overHidden: true,
          },
          {
            label: "结算单号",
            prop: "stlBillNo",
            type: "input",
            //sortable: true,
            overHidden: true,
          },
          // {
          //   label: "所属服务商",
          //   prop: "userType",
          //   slot: true,
          //   display: false,
            // overHidden: true,
          // },
          {
            label: "选择时间",
            prop: "timeData",
            type: "datetimerange",
            searchRange: true,
            format: "yyyy-MM-dd",
            valueFormat: "yyyy-MM-dd",
            startPlaceholder: "选择开始时间",
            endPlaceholder: "选择结束时间",
            search: true,
            clearable: false,
            searchValue: [dateFormat(new Date(new Date().getTime() - 3600 * 1000 * 24),"yyyy-MM-dd"), dateFormat(new Date(new Date().getTime() - 3600 * 1000 * 24),"yyyy-MM-dd")],
            pickerOptions: {
              disabledDate(time) {
                // const date = new Date();
                // let mTime = new Date(date.getFullYear(), date.getMonth() - 1, date.getDate())//上个月的今天
                return time.getTime() > Date.now();
              },
            },
            rules: [
              {
                required: true,
                message: "请选择时间段",
                trigger: "blur",
              },
            ],
            hide: true,
            display: false,
            overHidden: true,
          },
          {
            label: "商户号",
            prop: "mercId",
            type: "input",
            //sortable: true,
            rules: [{
              required: true,
              message: "请输入商户号",
              trigger: "blur"
            }],
            overHidden: true,
          },
          {
            label: "门头名称",
            prop: "mercName",
            type: "input",
            rules: [{
              required: true,
              message: "请输入门头名称",
              trigger: "blur"
            }],
            overHidden: true,
          },
          {
            label: "商户",
            prop: "rpiNo",
            type: "select",
            filterable: true,
            search: true,
            hide: true,
            display: false,
            rules: [
              {
                required: true,
                message: "请输入商户",
                trigger: "blur",
              },
            ],
            // props: {
            //   label: 'rpiName',
            //   value: 'rpiNo',
            //   desc:'rpiNo'
            // },
            // remote: true,
            // dicUrl: `/api/rb-oem/oem/incomingbasic/incoming_basic/list?current=-1&size=-1&rpiKind=0&rpiName={{key}}`,
            // dicFormatter:(data)=>{
            //   return data.data.records
            // },
            overHidden: true,
          },
          {
            label: "银行行号及名称",
            labelWidth: 130,
            prop: "bankName",
            type: "input",
            //sortable: true,
            hide: true,
            rules: [{
              required: true,
              message: "请输入银行行号及名称",
              trigger: "blur"
            }],
            overHidden: true,
          },
          {
            label: "卡类型",
            prop: "accountType",
            type: "select",
            dataType: "string",
            //sortable: true,
            hide: true,
            dicUrl: "/api/blade-system/dict/dictionary?code=ys_account_type",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            rules: [{
              required: true,
              message: "请输入卡类型",
              trigger: "blur"
            }],
            overHidden: true,
          },
          {
            label: "付款状态",
            prop: "payState",
            type: "select",
            dataType: "string",
            //sortable: true,
            search: true,
            // hide: true,
            dicUrl: "/api/blade-system/dict/dictionary?code=process_pay_state",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            rules: [
              {
                required: true,
                message: "请选择付款状态",
                trigger: "blur",
              },
            ],
            overHidden: true,
          },
          // {
          //   label: "付款状态",
          //   prop: "payState",
          //   //sortable: true,
          //   slot: true,
          //   display: false,
            // overHidden: true,
          // },
          {
            label: "结算类型",
            prop: "detailType",
            type: "select",
            dataType: "string",
            //sortable: true,
            dicUrl: "/api/blade-system/dict/dictionary?code=ys_detail_type",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            rules: [
              {
                required: true,
                message: "请选择结算类型",
                trigger: "blur",
              },
            ],
            overHidden: true,
          },
          {
            label: "结算金额",
            prop: "stlAmt",
            slot: true,
            overHidden: true,
          },
          {
            label: "付款金额",
            prop: "payAmt",
            slot: true,
            overHidden: true,
          },
          {
            label: "调整金额",
            prop: "adjustAmt",
            slot: true,
            overHidden: true,
          },
          {
            label: "商户手续费",
            labelWidth: 120,
            prop: "mercServiceAmt",
            slot: true,
            overHidden: true,
          },
        ]
      },
      data: [],
      excelForm: {},
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [{
          label: '模板上传',
          prop: 'excelFile',
          type: 'upload',
          drag: true,
          loadText: '模板上传中，请稍等',
          span: 24,
          propsHttp: {
            res: 'data'
          },
          tip: '请上传 .xls,.xlsx 标准格式文件',
          action: "/api/rb-oem/oem/invoicerecord/invoice_record/import"
        },
          {
            label: '模板下载',
            prop: 'excelTemplate',
            formslot: true,
            span: 24,
          }
        ]
      }
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.settlement_progress_add, false),
        viewBtn: this.vaildData(this.permission.settlement_progress_view, false),
        delBtn: this.vaildData(this.permission.settlement_progress_delete, false),
        editBtn: this.vaildData(this.permission.settlement_progress_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
  },
  watch: {
    "search.timeData"(val) {
      if (val) {
        this.search.stlStartDate = val[0].replace(/-/g, "");
        this.search.stlEndDate = val[1].replace(/-/g, "");
      }
    },
  },
  created() {
    this.loading = false;
  },
  methods: {
    // rowSave(row, done, loading) {
    //   // add(row).then(() => {
    //   //   this.onLoad(this.page);
    //   //   this.$message({
    //   //     type: "success",
    //   //     message: "操作成功!"
    //   //   });
    //   //   done();
    //   // }, error => {
    //   //   loading();
    //   //   window.console.log(error);
    //   // });
    // },
    // rowUpdate(row, index, done, loading) {
    //   // update(row).then(() => {
    //   //   this.onLoad(this.page);
    //   //   this.$message({
    //   //     type: "success",
    //   //     message: "操作成功!"
    //   //   });
    //   //   done();
    //   // }, error => {
    //   //   loading();
    //   //   window.console.log(error);
    //   // });
    // },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        // getDetail(this.form.id).then(res => {
        //   this.form = res.data.data;
        // });
      }
      done();
    },
    searchReset() {
      this.query = {};
      // this.onLoad(this.page);
    },
    searchChange(params, done) {
      if (!params.rpiNo) {
        this.$message({
          type: "warning",
          message: "请输入商户号!",
        });
      } else {
        this.query = params;
        this.page.pageNum = 1;
        this.onLoad(this.page, params);
      }
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.pageNum = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      if (!this.search.rpiNo) {
        this.$message({
          type: "warning",
          message: "请输入商户号!",
        });
      } else {
        this.onLoad(this.page, this.search);
      }
    },
    onLoad(page, params = {}) {
      // this.loading = true;
      getList(page.pageNum, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.infos;
        // this.loading = false;
        this.selectionClear();
      });
    },
    handleImport() {
      this.excelBox = true;
    },
    handleExport() {
      let exQuery = ``;
      exQuery += `&userNo=${this.search.userNo}`;
      exQuery += `&rirInvoiceCode=${this.search.rirInvoiceCode}`;
      exQuery += `&rirType=${this.search.rirType}`;
      exQuery += `&withdrawCode=${this.search.withdrawCode}`;
      this.$confirm("是否导出用户数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        window.open(
          `/api/rb-oem/oem/invoicerecord/invoice_record/export?${this.website.tokenHeader}=${getToken()}` + exQuery
        );
      });
    },
    handleTemplate() {
      window.open(`/api/rb-oem/oem/invoicerecord/invoice_record/export-template?${this.website.tokenHeader}=${getToken()}`);
    },
    uploadAfter(res, done) {
      this.excelBox = false;
      this.refreshChange();
      done();
    },
    uploadDelete(){
      return this.$confirm('是否确定移除该选项？');
    },
    sortChange(val) {
      if (val.order == "ascending") {
        //正序
        this.query.ascs = val.prop;
        this.query.descs = "";
      } else {
        //倒序
        this.query.descs = val.prop;
        this.query.ascs = "";
      }
      this.refreshChange();
    }
  }
};
</script>

<style lang="scss" scoped>
.money-text {
  color: #F56C6C;
  font-weight: bold;
}
</style>